const fs = require('fs')

const momentService = require('../service/moment_service')
const fileService = require('../service/file_service')
const {PICTURE_PATH} = require('../constants/file_path')

class MomentController {
  async create(ctx,next){
    const userId = ctx.user.id
    const content = ctx.request.body.content
    
    const result = await momentService.create(userId,content)
    ctx.body = result
  }

  async detail(ctx,next){
    // 获取数据
    const momentId = ctx.params.momentId
    // 根据id查询数据
    const result = await momentService.getMomentById(momentId)

    ctx.body = result
  }

  async list(ctx,next){
    const {limit,page} = ctx.query

    const result = await momentService.getMomentList(limit,page)

    ctx.body = result
  }

  async update(ctx,next){
    const { momentId } = ctx.params
    const { content } = ctx.request.body
    
    const result = await momentService.update(momentId,content)

    ctx.body = '修改成功'+result
  }
  
  async remove(ctx,next){
    const {momentId} = ctx.params

    const result = await momentService.remove(momentId)

    ctx.body = {
      message:'删除动态成功',
      data:result
    }
  }

  async addLabels(ctx,next){
    const {labels} = ctx
    const {momentId} = ctx.params
    // 添加所有标签
    for(let label of labels){
      // 判断标签是否与动态绑定
      const flag = await momentService.hasLabel(momentId,label.id)
      if(!flag){
        await momentService.addLabel(momentId,label.id)
      }
    }
    ctx.body = '标签添加成功'
  }

  async fileInfo(ctx,next){
    let {filename} = ctx.params
    const {type} = ctx.query
    const types = ["small","middle","large"]
    if(types.some(item => item == type)){
      filename = filename + '-' + type
    }
    const result = await fileService.getFileByFilename(filename)
    ctx.response.set('content-type',result.mimetype)
    ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`)
  }
}

module.exports = new MomentController()